package com.hitalkie.teacher.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.support.v7.widget.AppCompatButton;
import android.util.AttributeSet;

import com.hitalkie.teacher.R;

/**
 * Date 30/11/2016
 *
 * @author charliema
 */

public class TalkieButton extends AppCompatButton {

    public TalkieButton(Context context) {
        this(context, null);
    }

    public TalkieButton(Context context, AttributeSet attrs) {
        this(context, attrs, android.support.v7.appcompat.R.attr.buttonStyle);
    }

    public TalkieButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setup(attrs);
    }

    private void setup(AttributeSet attrs) {
        StateListDrawable stateBackground;

        Drawable drawable = getBackground();
        if (drawable != null && drawable instanceof StateListDrawable) {
            stateBackground = (StateListDrawable) drawable;
        } else {
            stateBackground = new StateListDrawable();
        }

        // attr
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.StateButton);

        // color
        int pressedBackgroundColor = typedArray.getColor(R.styleable.StateButton_pressedBackgroundColor, 0);

        // drawable
        GradientDrawable pressedBackground = new GradientDrawable();
        pressedBackground.setColor(pressedBackgroundColor);

        // state drawable
        if (isSetState(stateBackground, android.R.attr.state_pressed)) {
            return;
        } else {
            int[] states = new int[]{android.R.attr.state_enabled, android.R.attr.state_pressed};
            stateBackground.addState(states, pressedBackground);
        }

        setBackgroundDrawable(stateBackground);

        typedArray.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//        setRound(mRound);
    }

//    public void setRound(boolean round){
//        this.mRound = round;
//        int height = getMeasuredHeight();
//        if(mRound){
//            setRadius(height / 2f);
//        }
//    }

    private boolean isSetState(StateListDrawable stateBackground, int state) {
        int[] alreadyStates = stateBackground.getState();
        for (int s : alreadyStates) {
            if (s == state) {
                return true;
            }
        }
        return false;
    }

}
